package com.example.demojdbcmysql.config;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import java.util.Collection;

/**
 * @Description: 用户日志根据IP进行分库配置
 * @Author: kai.yang
 * @Date: 2019-10-26 13:40
 */
public class UserLogDbShardingAlgorithm implements PreciseShardingAlgorithm<String> {


    private static final String DB1 = "master1Config";

    private static final String DB2 = "master2Config";


    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        String dbNmame;
        String ip = shardingValue.getValue();
        int i = ip.hashCode();
        dbNmame = i % 2 == 0 ? DB1 : DB2;
        for (String each : availableTargetNames) {
            if (each.equals(dbNmame)) {
                return each;
            }
        }

        throw new IllegalArgumentException();
    }
}
